# coding=UTF-8
"""
Created on 2015年3月25日

@author: Administrator
"""
import hashlib
import time, os
import json
import traceback

from django.http.response import HttpResponse, HttpResponseRedirect
from django.shortcuts import render_to_response
from django.template import RequestContext
from django.db.models import Q
from django.views.decorators.csrf import csrf_exempt

from youaiwang.settings import BASE_DIR
from youaiwang.webapp_config import homeUrl
from forum.models import Sharing as SharingModel, Collection as CollectionModel
from lib.utils import do_logging, handle_uploaded_file, login
from account.models import User as UserDb, Lover as LoverDb, Message as MessageDb


def index(request):
    """
    注册页面
    :param request:
    :return:
    """
    if request.method == 'GET':
        return render_to_response('account/index.html', {},
                                  context_instance=RequestContext(request))
    else:
        myEmail = request.POST.get('myEmail', '')
        password = request.POST.get('password', '')
        loverToken = request.POST.get('loverToken', '')
        loverEmail = request.POST.get('loverEmail', '')
        return register(request, myEmail, password, loverToken, loverEmail)


@csrf_exempt
def show_login_page(request):
    if request.method == "GET":
        return render_to_response("account/login.html", {},
                                  context_instance=RequestContext(request))
    elif request.method == "POST":
        if request.is_ajax():
            email = request.POST.get('myEmail', '')
            password = request.POST.get('password', '')
            password = hashlib.md5(password).hexdigest()
            # 存在则登录成功
            try:
                user = UserDb.objects.get(email=email, password=password, status=1)
                now = time.strftime('%Y%m%d%H%M%S', time.localtime(time.time()))
                user.loginToken = hashlib.md5(user.password + now).hexdigest()
                user.save()
                saveSession(user, request)
                return HttpResponse(json.dumps({
                    "code": 1,
                    "redirect": homeUrl
                }))
            # 登录失败
            except UserDb.DoesNotExist as e:
                do_logging('error', e)
                return HttpResponse(json.dumps({
                    "code": 2,
                    "login_tips": u'账号或者密码错误！'
                }))
    return render_to_response("account/login.html", {},
                              context_instance=RequestContext(request))


# 获取用户信息
def get_user_msg(request, userId):
    obj = {}
    if request.method == "GET":
        # 若是用户自身
        if userId == str(request.session.get('userId', '')):
            return get_profile(request)
        else:
            obj['session'] = request.session
            try:
                user = UserDb.objects.get(id=userId, status=True)
                loverRecord = LoverDb.objects.get(Q(firstLover=user) | Q(secondLover=user), status=True)
                if user.nickname == loverRecord.firstLover.nickname:
                    obj['lover'] = loverRecord.secondLover
                else:
                    obj['lover'] = loverRecord.firstLover
                obj["loveStatus"] = "恋爱ing"  # 说明用户是否为单身
                if loverRecord.firstLover.email == loverRecord.secondLover.email:
                    obj["loveStatus"] = "自恋ing"
                obj['togeTime'] = loverRecord.createTime.strftime("%Y/%m/%d") \
                                  + '至' + time.strftime('%Y/%m/%d', time.localtime(time.time()))
                obj['user'] = user
            except LoverDb.DoesNotExist:
                obj["loveStatus"] = "单身ing"
        return render_to_response('account/user.html',
                                  {'obj': obj},
                                  context_instance=RequestContext(request))


# def countDate(startTime, nowTime):
# pass
# # print datetime(startTime[0],startTime[1],startTime[2])-datetime(nowTime[0],nowTime[1],nowTime[2])



def get_profile(request):
    obj = {}
    if request.method == "GET":
        if request.session.get('webStatus', '') == 'HasLogin':
            obj['session'] = request.session
            userId = request.session.get('userId')
            try:

                user = UserDb.objects.get(id=userId, status=1)
                obj['user'] = user
                loverRecord = LoverDb.objects.get(Q(firstLover=user) | Q(secondLover=user), status=True)
                if user.nickname == loverRecord.firstLover.nickname:
                    obj['lover'] = loverRecord.secondLover
                else:
                    obj['lover'] = loverRecord.firstLover
                obj["loveStatus"] = "恋爱ing"  # 说明用户是否为单身
                if loverRecord.firstLover.nickname == loverRecord.secondLover.nickname:
                    obj["loveStatus"] = "自恋ing"
                obj['togeTime'] = loverRecord.createTime.strftime("%Y/%m/%d") + \
                                  '至' + time.strftime('%Y/%m/%d', time.localtime(time.time()))
                obj['user'] = user
            except Exception as e:
                do_logging('error', e, traceback.format_exc())
                obj["loveStatus"] = "单身ing"
        return render_to_response('account/profile.html',
                                  {'obj': obj},
                                  context_instance=RequestContext(request))

    elif request.method == "POST":
        if request.session.get('webStatus', '') == 'HasLogin':
            userId = request.session.get('userId')
            nickname = request.POST.get('nickname_input', str(userId))
            try:
                user = UserDb.objects.get(id=userId, status=1)

                user.nickname = nickname
                user.save()
                saveSession(user, request)
                return HttpResponseRedirect('/account/profile/')
            except UserDb.DoesNotExist:
                return HttpResponse("数据库保存不成功！")
        else:
            return HttpResponse("UPLOAD FAILED!")


def upload_portraitUri(request, userId):
    if request.method == "POST":
        if (request.session.get("webStatus", '') == "HasLogin") and request.FILES.get('headimg'):

            path = BASE_DIR + '/static/upload/' + str(userId)
            if not os.path.exists(path):
                os.makedirs(path)
            absolute_path_filename = path + '/headimg.' + request.FILES['headimg'].name.split('.')[-1]
            handle_uploaded_file(request.FILES['headimg'], absolute_path_filename)
            try:
                user = UserDb.objects.get(id=userId, status=1)
                user.portraitUri = absolute_path_filename.replace(BASE_DIR, '')
                user.save()
                saveSession(user, request)
                return HttpResponseRedirect('/account/profile/' + userId + "/")
            except Exception as e:
                do_logging('error', e, traceback.format_exc())
                raise


def loginbyemail(request):
    # POST
    if request.method == "POST":
        email = request.POST.get('email_input', '')
        password = request.POST.get('password_input', '')
        password = hashlib.md5(password).hexdigest()
        # 存在则登录成功
        try:
            user = UserDb.objects.get(email=email, password=password, status=1)
            now = time.strftime('%Y%m%d%H%M%S', time.localtime(time.time()))
            user.loginToken = hashlib.md5(user.password + now).hexdigest()
            user.save()
            saveSession(user, request)
            return HttpResponseRedirect('/home/')
        # 登录失败
        except Exception as e:
            do_logging('error', e, traceback.format_exc())
            return HttpResponse('login failed!')


def saveSession(user, request):
    request.session["webStatus"] = 'HasLogin'
    request.session["userId"] = user.id
    request.session["email"] = user.email
    request.session["nickname"] = user.nickname
    request.session["loginToken"] = user.loginToken
    request.session["portraitUri"] = user.portraitUri


def register(request, myEmail, password, loverOath, loverEmail):
    # POST
    if request.method == "POST":
        # 若存在则无法注册，需要换邮箱
        try:
            UserDb.objects.get(email=myEmail, status='True')
            obj = {
                'tipForEmail': '该邮箱已被注册'
            }
            return render_to_response('account/index.html', {'obj': obj}, context_instance=RequestContext(request))
        # 利用异常判断是否已被注册：不存在，可以注册，帐号最少有一天的有效期
        except UserDb.DoesNotExist:
            now = time.strftime('%Y%m%d%H%M%S', time.localtime(time.time()))
            user = UserDb(
                email=myEmail,
                password=hashlib.md5(password).hexdigest(),
            )
            user.save()
            user.loginToken = hashlib.md5(user.password + now).hexdigest()
            user.nickname = u"用户%s" % hashlib.md5(str(user.id)).hexdigest()[:6]
            user.save(update_fields=['loginToken', 'nickname'])
            saveSession(user, request)
            # 若存在证明有人先发布情侣号
            try:
                lover = LoverDb.objects.get(status=1, loveOath=hashlib.md5(myEmail + loverOath).hexdigest())
                lover.secondLover = user
                lover.secondLoverEmail = myEmail
                lover.save()
                return HttpResponseRedirect(homeUrl)
            # 不存在，需要本人去创建情侣号
            except Exception as e:
                print "Exception:", e
                lover = LoverDb()
                lover.firstLover = user
                lover.secondLover = user
                lover.firstLoverEmail = myEmail
                lover.loveOath = hashlib.md5(loverEmail + loverOath).hexdigest()
                lover.save()
                # 创建情侣号成功
                return HttpResponseRedirect(homeUrl)


def isEmailExist(request, email):
    if request.method == "GET":
        try:
            UserDb.objects.get(email=email, status=1)
            tipForEmail = '该邮箱已被注册'
            return HttpResponse(tipForEmail)
        # 不存在，可以注册，帐号最多有一天的有效期
        except UserDb.DoesNotExist as e:
            do_logging(e)
            tipForEmail = ''
            return HttpResponse(tipForEmail)


def logout(request):
    if request.session.get('webStatus'):
        del request.session['webStatus']
    if request.session.get('userId'):
        del request.session['userId']
    if request.session.get('email'):
        del request.session['email']
    if request.session.get('nickname'):
        del request.session['nickname']
    if request.session.get('loginToken'):
        del request.session['loginToken']
    if request.session.get('portraitUri'):
        del request.session['portraitUri']
    return HttpResponseRedirect(homeUrl)


def get_messages(request):
    if request.method == "GET":
        userId = request.session.get('userId', '')
        user = UserDb.objects.get(id=userId, status=True)
        msgListIter = MessageDb.objects.filter(Q(originUser=user) | Q(toPer=user)). \
            exclude(fromPer=user). \
            order_by('-createTime')

        msgCount = msgListIter.filter(status=True).count()
        obj = {
            'msgCount': msgCount,
            'msgList': msgListIter,
            'session': request.session
        }

        # return HttpResponse(json.dumps(obj))
        return render_to_response('account/message.html', {'obj': obj}, context_instance=RequestContext(request))
    else:
        if request.method == "POST":
            return loginbyemail(request)
        return HttpResponse('Neither GET NOR POST!')


def get_user_sharing(request, userId):
    obj = {}
    if request.method == "GET":
        obj['session'] = request.session
        try:
            user = UserDb.objects.get(id=userId, status=True)
            sharingIter = SharingModel.objects.filter(author=user, status=True)
            obj['sharingList'] = sharingIter
            return render_to_response('account/user_sharing.html', {"obj": obj},
                                      context_instance=RequestContext(request))
        except Exception as e:
            do_logging("error", e, traceback.format_exc())
            return HttpResponse(500)


def get_user_collection(request):
    obj = {}
    if request.method == "GET":
        obj['session'] = request.session
        try:
            userId = request.session.get('userId')
            user = UserDb.objects.get(id=userId)
            collectionIter = user.collection_set.all()
            obj['collectionList'] = collectionIter
            return render_to_response('account/user_collection.html', {'obj': obj})
        except Exception as e:
            do_logging("error", e, traceback.format_exc())
            return HttpResponse('Server Error!')


if __name__ == '__main__':
    pass
